package com.liu.QQ.server;


import com.liu.QQ.Message;
import com.liu.QQ.User;
import com.liu.QQ.server.service.ManageServerThread;
import com.liu.QQ.server.service.ServerConnectThread;
import com.liu.QQ.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 监听9999，等待客户端连接，并保持通信
 * @author liuchengjie
 */
@SuppressWarnings({"all"})
public class QQserver {

    private ServerSocket serverSocket = null;

    public static void main(String[] args) {
        new QQserver();
    }
    public QQserver() {
        System.out.println("服务器在9999端口监听");
        try {
            serverSocket = new ServerSocket(9999);
            while (true) {
                //循环监听，和某个客户端建立连接后，会继续监听
                Socket socket = serverSocket.accept();
                //去读取信息
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                User user = (User)objectInputStream.readObject();
                Message message = new Message();
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                //验证
                if (user.getPassword().equals("123456")) {
                    //验证通过
                    message.setMesType(MessageType.MESSAGE_LOGIN_SUCCEED);
                    outputStream.writeObject(message);
                    //创建一个线程和客户端保持通信,持有socket
                    ServerConnectThread serverConnectThread = new ServerConnectThread(socket, user.getUserId());
                    serverConnectThread.start();
                    //将线程对象放入集合中进行管理
                    ManageServerThread.addConnectThread(user.getUserId(),serverConnectThread);
                } else {
                    //登录失败
                    message.setMesType(MessageType.MESSAGE_LOGIN_FAIL);
                    outputStream.writeObject(message);
                    socket.close();
                }
            }

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            //服务端退出while循环，不再监听，关闭资源
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
